import React, { useEffect } from 'react'
import { Layout } from 'antd'
import { connect } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { changeLuckySheetOption, changeUpdateDate } from '../../redux/actionCreator/lineLossFillActionCreater'
import axios from 'axios'
import moment from 'moment'


const { Content } = Layout
// 表格体
function LuckySheetContent (props) {

  // 编程式跳转
  const navigate = useNavigate()
  const defaultOption = {
    container: "luckysheet",
    lang: 'zh',
    showinfobar: false
  }



  //将状态和方法解构出来,直接使用
  let { luckySheetOption, changeLuckySheetOption, changeUpdateDate } = props

  //获取报表
  const getReports = async () => {
    await axios.post(
      "http://localhost:8081/system/lineLossFill/getReport",
      {
        username: localStorage.getItem("username"),
        date: moment().format('YYYY-MM')
      },
      {
        Pragma: 'no-cache',
        headers: { 'satoken': localStorage.getItem("satoken") }
      },
      {
        responseType: 'blob'
      }

    ).then(r => {

      console.log(r)
      if (r.status === 200 && !r.data.code) {
        //获取华东的数据

        defaultOption.data = r.data
        changeLuckySheetOption(JSON.stringify(defaultOption))

      } else if (r.data.code === 500) {
        console.log(1111)
        navigate('/login')
      }
    })
  }

  // 获取填报时间
  const getInsertTime = async () => {
    await axios.get("http://localhost:8081/system/lineLossFill/getFillDate",
      {
        params: {
          username: localStorage.getItem("username"),
          month: moment().format('YYYY-MM')
        },
        headers: {
          satoken: localStorage.getItem("satoken")
        }
      }
    ).then(r => {
      if (r.data.code === 200) {
        changeUpdateDate(r.data.data)
      }
    })
  }

  // 在组件挂载时渲染
  useEffect(() => {
    // 如果redux中的配置有数据就直接用缓存渲染，如果没有再去从后端获取
    if (luckySheetOption !== "") {

      if (window.luckysheet.getAllSheets().length !== 0) {
        window.luckysheet.destroy()
      }
      // 创建
      window.luckysheet.create(JSON.parse(luckySheetOption))

    } else {
      //查询网损月报
      getReports()
      // 获取提交的时间
      getInsertTime()
    }

  }, [luckySheetOption])

  // 报表样式
  const luckyCss = {
    margin: '0px',
    padding: '0px',
    position: 'relative',
    width: '100%',
    height: '100%',
    left: '0px'
  }

  return (
    <Content className="site-layout" style={{ padding: 0, height: '90%' }}>

      <div id='luckysheet' style={luckyCss}>

      </div>

    </Content>
  )
}
// 将state映射到props中
const mapStateToProps = (state) => {
  return {
    luckySheetOption: state.LineLossFillReducer.luckySheetOption,

  }
}

//这是修改redux状态的方法
const mapDispatchToProps = {
  changeLuckySheetOption,
  changeUpdateDate
}

export default connect(mapStateToProps, mapDispatchToProps)(LuckySheetContent)